package qfpay

import (
    "fmt"
    "sort"
	"errors"
	"strconv"
	"strings"
	"crypto/md5"
	"thirdpaysdk/utils/mapstruct"
)

type QfPayMsg struct {
	Status     string  `json:"status"`
	Sysdtm     string  `json:"sysdtm"`
	Paydtm     string  `json:"paydtm"`
	GoodsName  string  `json:"goods_name"`
	Txcurrcd   string  `json:"txcurrcd"`
	Mchid      string  `json:"mchid"`
	Cancel     string  `json:"cancel"`
	PayType    string  `json:"pay_type"`
	Cardcd     string  `json:"cardcd"`
	Txdtm      string  `json:"txdtm"`
	Txamt      string  `json:"txamt"`
	OutTradeNo string  `json:"out_trade_no"`
	Syssn      string  `json:"syssn"`
	Respcd     string  `json:"respcd"`
	GoodsInfo  string  `json:"goods_info"`
	NotifyType string  `json:"notify_type"`
}

func notifysign(fields map[string]string, privateKey string) string {
    basestring := ""
	var keys []string
	for k := range fields {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		basestring += k + "=" + fields[k] + "&"
	}
	midstring := strings.TrimSuffix(basestring, "&") + "privateKey"
	sign := fmt.Sprintf("%X", md5.Sum([]byte(midstring)))
	return sign
}

func QfPayNotify(response *QfPayMsg,privateKey string) (map[string]interface{}, error){
	var paramsMap map[string]string
	paramsMap = make(map[string]string)
	
	rspMap := mapstruct.Struct2Map(response, "json")
	for k, v := range rspMap {
		if s, ok := v.(string); ok {
			paramsMap[k] = s
		} else if _, ok := v.(int); ok {
			paramsMap[k] = strconv.Itoa(v.(int))
		} else {
			err := errors.New("格式错误，map 格式只支持string, int")
			return rspMap, err
		}
	}
	sign := notifysign(paramsMap, privateKey)
	fmt.Println(sign)
	return rspMap, nil
}


